import 'dart:async';
import 'package:flutter/material.dart';
import 'package:my_first_app/utils/app_logger.dart';
import 'main_screen.dart';


class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  static const int _countdownSeconds = 5; // 倒计时5秒
  int _remainingSeconds = _countdownSeconds;
  Timer? _timer;

  final logger = AppLogger();

  @override
  void initState() {
    super.initState();
    // 启动倒计时
    _startCountdown();
  }

  @override
  void dispose() {
    _timer?.cancel(); // 避免内存泄漏
    super.dispose();
  }

  // 开始倒计时
  void _startCountdown() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_remainingSeconds <= 1) {
        timer.cancel();
        // 倒计时结束，跳转到主页面
        _navigateToMain();
      } else {
        setState(() {
          _remainingSeconds--;
        });
      }
    });
  }

  // 跳转到主页面
  void _navigateToMain() {
    logger.info('已经进入主界面');
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (context) => MainScreen()),
    );
  }

  // 手动跳过广告
  void _skipAd() {
    logger.info('已经手动跳过广告');
    _timer?.cancel();
    _navigateToMain();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // 全屏背景广告图
          SizedBox.expand(
            child: Image.asset(
              'assets/images/splash_ad.png',
              fit: BoxFit.cover, // 图片覆盖全屏
            ),
          ),
          // 右上角跳过按钮
          Positioned(
            top: 60.0,
            right: 20.0,
            child: GestureDetector(
              onTap: _skipAd,
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 12.0,
                  vertical: 6.0,
                ),
                decoration: BoxDecoration(
                  color: Colors.black.withValues(alpha: 0.5),
                  borderRadius: BorderRadius.circular(20.0),
                ),
                child: Text(
                  _remainingSeconds > 0
                      ? '跳过 ${_remainingSeconds}s'
                      : '跳过',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 14.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}